#include <jni.h>
#include <string>


#include "ScanFiles.h"
#include "DzLog.h"

#define LOG_TAG "scranJni"

extern "C"
jobjectArray
Java_com_example_gavin_scanfiles_ScanFileActivity_getFileTypeList(JNIEnv *env,
                                                                  jobject /* this */,
                                                                  jstring fileType_
                                                                  ) {
    const char *fileType = env->GetStringUTFChars(fileType_, 0);
    LOGD("getFile Type:%s",  fileType);
    list<string> *mp3List = ScanFiles::getInterface()->getFileTypeList(fileType);

    jclass stringArrCls = env->FindClass("java/lang/String");
    jobjectArray  fileList = env->NewObjectArray((*mp3List).size(), stringArrCls, NULL);

    int index = 0;
    if (mp3List != NULL) {
        list<string>::iterator fileName;
        for (fileName=(*mp3List).begin();fileName!=(*mp3List).end();fileName++){
            jstring jpath = env->NewStringUTF((*fileName).c_str());
            env->SetObjectArrayElement(fileList,index, jpath);
            env->DeleteLocalRef(jpath);
            index ++;
        }
    }

    env->ReleaseStringUTFChars(fileType_, fileType);

    return fileList;
}

/**
 * 获取对应后缀的文件列表
 */
extern "C"
jstring Java_com_example_gavin_scanfiles_ScanFileActivity_stringFromJNI(
        JNIEnv *env,
        jobject /* this */) {
    std::string hello = "Hello from C++";
    return env->NewStringUTF(hello.c_str());
}

/**
 * 初始化并扫描对应目录文件
 */
extern "C"
jint Java_com_example_gavin_scanfiles_ScanFileActivity_initPath(
        JNIEnv *env,
        jobject /* this */,
        jstring j_path,
        jobjectArray strArray
        ) {

    const char *c_path = NULL;
    jboolean isCopy;    // 返回JNI_TRUE表示原字符串的拷贝，返回JNI_FALSE表示返回原字符串的指针
    c_path = env->GetStringUTFChars(j_path, &isCopy);
    if (c_path == NULL) {
        return NULL;
    }

    list<string> fileTypeList;
    fileTypeList.clear();
    jstring jstr;
    jsize len = env->GetArrayLength(strArray);
    char const **pstr = (char const**) malloc(len*sizeof(char *));
    for (int i=0 ; i<len; i++) {
        jstr = (jstring)env->GetObjectArrayElement(strArray, i);
        pstr[i] = env->GetStringUTFChars(jstr, 0);
        fileTypeList.push_back(pstr[i]);
        env->ReleaseStringUTFChars(jstr, pstr[i]);
    }

    ScanFiles *scanFiles = ScanFiles::getInterface();
    scanFiles->init(c_path, fileTypeList);
    env->ReleaseStringUTFChars(j_path, c_path);

    return 0;
}


